<?php

declare (strict_types=1);
namespace app\admin\http\middleware;

use app\common\enum\SysEnum;
use app\common\facade\JwtAuth;
use app\common\facade\Response as ResponseFacade;
use think\facade\Cache;
use Closure;
class SysUserLoginMiddleware
{
    //  不需要验证的接口
    public array $notLoginApi = ['login/login','login/phonelogin','login/sendcode','upload/uploadImage','upload/uploadFile','login/getSetting','login/sendEmail','server.apply/edit','update/checkver'];

    /**
     * 登录请求请求验证
     * @param Request   $request
     * @param Closure   $next
     * @return \think\Response
     */
    public function handle($request, Closure $next,)
    {
        //传入token
        $header = $request->header();
        $token = '';
        if (isset($header['authorization'])) $token = str_replace('Bearer ', '', $header['authorization']);

        $apiUrl = strtolower($request->controller()) . '/' . $request->action();
        $request->isNotLogin=in_array(trim($apiUrl), $this->notLoginApi);
        
        if ( !$request->isNotLogin && empty($token)) {
            //没有token并且该地址需要登录才能访问
          return  ResponseFacade::error('请求缺少参数token_login',[],401);
        }
        if($token){
            //验证Token 是否过期
            $user = JwtAuth::verify($token);

            if (!$user) {
                return  ResponseFacade::error('请重新登录',[], 401);
            }
            $cacheToken = Cache::get(SysEnum::OWN_USIGN.$user->uid);
            if (!$cacheToken || $cacheToken != $token) {
                return  ResponseFacade::error('你已被登出，请重新登录',[], 401);
            }
            $request->uid = (int) $user->uid;
            $request->auth = $user;
        }
        return $next($request);
    }


}